package com.hthy.futures.ui.activity;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.base.BaseActivity;
import com.hthy.futures.base.CommonAdapter;
import com.hthy.futures.base.CommonViewHolder;
import com.hthy.futures.bean.AppConfigContext;
import com.hthy.futures.bean.PageBean;
import com.hthy.futures.bean.SaveAppContext;
import com.hthy.futures.utils.AppOperator;
import com.hthy.futures.utils.CacheManager;
import com.hthy.futures.utils.GlideUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.SPUtils;
import com.hthy.futures.view.TitleView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import okhttp3.Call;
import okhttp3.Request;

import static com.hthy.futures.R.id.listView;
import static com.hthy.futures.utils.TDevice.dp2px;


/**
 * 此判断设计为刚进去的时候为空列表，通过搜索交易商代码，请求接口，得到交易所数据，一般也就一个信息而已。
 * 当选择信息的时候，要保存在本地数据库文件中，下次进来的时候直接展示在列表中（列表中的数据代表选择的历史数据）
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/5/17
 */


/**
 * 思路整理：其中一个解决方案就是首次进去的时候看看有没有保存值（请求的值），如果有的话
 * <p>
 * 遇到不能保存文件（app从后台删除就不能保存了），这是怪事了。
 * 通过另外一种写法就行了，不懂啥原因？？？
 */

public class SearchActivity extends BaseActivity {

    @Bind(R.id.floating_search_view)
    FloatingSearchView mSearchView;
    @Bind(R.id.titleview)
    TitleView mTitleView;

    @Bind(listView)
    SwipeMenuListView mListView;
    @Bind(R.id.iv_trade_img)
    ImageView mIvTradeImg;
    @Bind(R.id.tv_trade_name)
    TextView mTvTradeName;
    @Bind(R.id.ll_item)
    RelativeLayout mLlItem;
    private CommonAdapter mSearchAdapter;

    private AppConfigContext mMAppConfigContext;
    private static OnServiceItemSelectedListener mServiceItemListner;
    private List<AppConfigContext> mAppConfigContexts;


    protected String CACHE_NAME = getClass().getName();
    protected PageBean<AppConfigContext> mBean;

    @Override
    protected int getContentView() {
        return R.layout.activity_search;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mLlItem.setVisibility(View.GONE);

        mTitleView.setBackBtn();
        mTitleView.setTitle("选择交易商");

        mSearchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
            @Override
            public void onSearchTextChanged(String oldQuery, final String newQuery) {
                //get suggestions based on newQuery

                //pass them on to the search view
                //mSearchView.swapSuggestions(newSuggestions);

                // 请求交易中心json数据
                OkHttpUtils
                        .get()//
                        .url(AppConfig.TEADE_CENTER)//
                        .addParams(getString(R.string.query_type), getString(R.string.config))
                        .addParams(getString(R.string.query_data), newQuery)
                        .build()//
                        .execute(new MyStringCallback());
            }
        });

        mSearchView.setOnMenuItemClickListener(new FloatingSearchView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemSelected(MenuItem item) {

            }
        });

        mSearchAdapter = new CommonAdapter<AppConfigContext>(this, R.layout.adap_search) {
            @Override
            public void convert(CommonViewHolder vh, AppConfigContext item) {
                vh.setText(R.id.tv_trade_name, item.getExch_name());
                vh.setImageForUrl(R.id.iv_trade_img, item.getLogo_uri());
            }
        };
        mListView.setAdapter(mSearchAdapter);

        // 读取缓存文件mAppConfigContexts
        mBean = (PageBean<AppConfigContext>) CacheManager.readObject(this, CACHE_NAME);
        if (mBean == null) {
            mBean = new PageBean<>();
            mBean.setItems(new ArrayList<AppConfigContext>());
        }
        mAppConfigContexts = mBean.getItems();

        if (mAppConfigContexts == null) {
            mAppConfigContexts = new ArrayList<>();
        }

        if (mAppConfigContexts != null && mAppConfigContexts.size() > 0) {
            mSearchAdapter.addItem(mAppConfigContexts);
            mListView.setVisibility(View.VISIBLE);
        }

        // 当点击搜索的条目时，第一要记录到list中，第二修改整个环境，然后跳到登录页面
        //
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 修改整个环境，然后跳到登录页面
                // 还要进行滑动删除
                AppConfigContext appConfigContext = (AppConfigContext) mSearchAdapter.getItem(position);

                onresponseChoose(appConfigContext);

            }
        });

        mLlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isNeedAdd = false;
                // 首先去历史记录里面去查询，如果如果AppId如果相同的话，就不添加
                if (mAppConfigContexts!=null&&mAppConfigContexts.size() > 0) {
                    for (AppConfigContext appConfigContext : mAppConfigContexts) {
                        if (appConfigContext.getAppId().equals(mMAppConfigContext.getAppId())) {
                            isNeedAdd = true;
                        }
                    }
                    if (!isNeedAdd) {
                        mAppConfigContexts.add(mMAppConfigContext);
                    }
                } else {
                    mAppConfigContexts.add(mMAppConfigContext);
                }

                // 保存到本地文件中
                saveAppConfigContexts(mAppConfigContexts);

                onresponseChoose(mMAppConfigContext);
            }
        });


        // 当监听到取消搜索的的操作时要显示listview控件

        initSwipList();
    }

    private void saveAppConfigContexts(List<AppConfigContext> appConfigContexts) {
        mBean.setItems(appConfigContexts);
        CacheManager.saveObject(SearchActivity.this, mBean, CACHE_NAME);
    }

    private void onresponseChoose(AppConfigContext appConfigContext) {
        // 现在只有两种选择，如果到时候有多个该怎么书写
        String appId = appConfigContext.getAppId();
        if ("hthy".equals(appId)) {
            AppContext.tongnanEnv = false;
        } else {
            AppContext.tongnanEnv = true;
        }
        AppConfig.query_data = appId;
        SPUtils.saveToPrefs(SearchActivity.this, AppConfig.query_data, appId);
        SPUtils.saveToPrefs(AppContext.context(), AppConfig.logo ,appConfigContext.getLogo_uri());
        if (mServiceItemListner != null) {
            mServiceItemListner.onselect(appConfigContext);
        }

        finish();
    }

    /**
     * swipmenulistview使用
     */
    private void initSwipList() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

// set creator
        mListView.setMenuCreator(creator);

        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        AppConfigContext appConfigContext = mAppConfigContexts.get(position);
                        mAppConfigContexts.remove(appConfigContext);
                        saveAppConfigContexts(mAppConfigContexts);
                        mSearchAdapter.removeItem(position);
                        break;
                }
                return false;
            }
        });
    }


    /**
     * 请求回调
     */
    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request, int id) {
            //DialogUtil.showDialog(SearchActivity.this);
        }

        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(String response, int id) {
            LogUtils.e("config", response);
            //AppContext.parseJson(response);
            mLlItem.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);

            mMAppConfigContext = AppContext.createGson().fromJson(response, AppConfigContext.class);
            mTvTradeName.setText(mMAppConfigContext.getExch_name());
            GlideUtils.setImageCenter(SearchActivity.this, mMAppConfigContext.getLogo_uri(), mIvTradeImg);
        }
    }


    public static void setOnServiceSelected(OnServiceItemSelectedListener onServiceItem) {
        mServiceItemListner = onServiceItem;
    }

    public interface OnServiceItemSelectedListener {
        void onselect(AppConfigContext appconfigContext);
    }

}